package com.livsdesign.tools.condition

import android.content.Context
import android.content.pm.PackageManager
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import java.lang.IllegalArgumentException
import java.lang.ref.WeakReference

/**
 * ``` build.gradle
 * // 在 https://developer.android.google.cn/jetpack/androidx/releases/activity 获得最新版本号
 * def activity_version = "1.2.2"
 * // 在 https://developer.android.google.cn/jetpack/androidx/releases/fragment 获得最新版本号
 * def fragment_version = "1.3.2"
 * implementation "androidx.activity:activity:$activity_version"
 * implementation "androidx.fragment:fragment:$fragment_version"
 * ```
 * **扩展阅读**
 * 1. [使用 Jetpack ActivityResult 处理 Activity 之间的数据通信](https://mp.weixin.qq.com/s/lAnzLddefDqbR1Je09lP9A)
 * 2. [Jetpack ActivityResult](https://developer.android.google.cn/training/basics/intents/result#register)
 */

typealias OnPermissionResultCallback = (isGrand: Boolean, neverAck: Boolean) -> Unit

class PermissionUtils(obj: Any) {

    private val launcher: ActivityResultLauncher<String>
    private var objectWeakRef: WeakReference<Any> = WeakReference(null)
    private var callback: OnPermissionResultCallback? = null

    init {
        objectWeakRef = WeakReference(obj)
        launcher = when (obj) {
            is Fragment -> obj.registerForActivityResult(ActivityResultContracts.RequestPermission()) {
                handleCallback(it)
            }
            is FragmentActivity -> obj.registerForActivityResult(ActivityResultContracts.RequestPermission()) {
                handleCallback(it)
            }
            else -> throw IllegalArgumentException("context must be Fragment,FragmentActivity")
        }
    }

    /**
     * 在Android 11之前权限有一个选项是"拒绝并再也不询问"
     * android11开始后，拒绝两次后就会变成再也不询问了
     */
    private fun handleCallback(isGrand: Boolean) {
        val permission = currentPermission ?: return
        callback?.invoke(isGrand, neverAck(permission))
    }

    fun checkPermissions(vararg permissions: String): Boolean {
        return permissions.all {
            ContextCompat.checkSelfPermission(
                requestContext(),
                it
            ) == PackageManager.PERMISSION_GRANTED
        }
    }

    private var currentPermission: String? = null
    fun requestPermission(permission: String, callback: OnPermissionResultCallback) {
        currentPermission = permission
        this.callback = callback
        launcher.launch(permission)
    }

    private fun requestContext(): Context {
        val obj = objectWeakRef.get() ?: throw IllegalArgumentException("context has been recycle")
        return when (obj) {
            is Fragment -> obj.requireContext()
            is FragmentActivity -> obj
            else -> throw IllegalArgumentException("context must be Fragment,FragmentActivity")
        }
    }

    //Android 11中第一次获取此方法会返回false，第一次被拒绝后为调用返回true，第二次拒绝后调用返回false（此时已是再也不询问所有也没必要show）,只有卸载或者清除缓存才会重置
    private fun shouldShowRequestPermissionRationale(permission: String): Boolean {
        val obj = objectWeakRef.get() ?: throw IllegalArgumentException("context has been recycle")
        return when (obj) {
            is Fragment -> obj.shouldShowRequestPermissionRationale(permission)
            is FragmentActivity -> ActivityCompat.shouldShowRequestPermissionRationale(
                obj,
                permission
            )
            else -> false
        }
    }

    /**
     * @see shouldShowRequestPermissionRationale
     * 此处为第一次
     */
    private fun neverAck(permission: String): Boolean {
        return !shouldShowRequestPermissionRationale(permission)
    }
}